﻿using System;
using NHibernate.Event;
using Xenta.Entities;
using Xenta.Events;
using Xenta.Utils;

namespace Xenta.Triggers
{
    internal class AfterSalesOptionUpdated : Trigger<NHibernateEvent<PostUpdateEvent>>
    {
        #region Utilities

        protected override void Handler(NHibernateEvent<PostUpdateEvent> evt)
        {
            if(!(evt.Arg.Entity is SalesOptionEntity))
                return;

            var option = evt.Arg.Entity as SalesOptionEntity;
            var oldPrice = (decimal)evt.Arg.GetOldPropertyValue("Price");
            if(option.Price == oldPrice) 
                return;

            foreach(var i in option.ShoppingCartItems)
            {
                evt.Source.CreateSQLQuery("exec fwk_ShoppingCartItems_UpdateTotal @ItemID=:ItemID, @UpdatedOn=:UpdatedOn")
                   .SetInt32("ItemID", i.EntityID)
                   .SetDateTime("UpdatedOn", DateTime.UtcNow)
                   .ExecuteUpdate();
                evt.Source.CreateSQLQuery("exec fwk_ShoppingCarts_UpdateTotal @CartID=:CartID, @UpdatedOn=:UpdatedOn")
                   .SetInt32("CartID", i.Cart.EntityID)
                   .SetDateTime("UpdatedOn", DateTime.UtcNow)
                   .ExecuteUpdate();
            }
            foreach(var i in option.ShoppingCarts)
            {
                evt.Source.CreateSQLQuery("exec fwk_ShoppingCarts_UpdateTotal @CartID=:CartID, @UpdatedOn=:UpdatedOn")
                   .SetInt32("CartID", i.EntityID)
                   .SetDateTime("UpdatedOn", DateTime.UtcNow)
                   .ExecuteUpdate();
            }
        }

        #endregion
    }
}
